package com.itmuch.icms.controller.front.user;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itmuch.core.constants.SessionConstants;
import com.itmuch.core.util.SaltUtil;
import com.itmuch.core.web.converter.Result;
import com.itmuch.icms.user.domain.User;
import com.itmuch.icms.user.service.IUserService;
import com.itmuch.icms.user.vo.UserRegVo;

/**
 * 用户注册
 * @author ITMuch
 */
@Controller
public class RegisterController {
    @Resource
    private IUserService userService;

    private static final int SALT_SIZE = 8;

    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public String regInput() {
        return "default/user/reg";
    }

    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    @ResponseBody
    public Result reg(@RequestBody UserRegVo userRegVo, HttpSession session) throws Exception {
        Assert.isTrue(userRegVo.getPassword().equals(userRegVo.getPassword1()), "两次输入密码不同.");
        String captcha = userRegVo.getCaptcha();
        String getC = (String) session.getAttribute(SessionConstants.KAPTCHA_SESSION_KEY);
        Assert.isTrue(captcha.equalsIgnoreCase(getC), "验证码输入不正确");
        User user = new User();
        user.setUsername(userRegVo.getUsername());
        user.setEmail(userRegVo.getEmail());
        String saltString = SaltUtil.genSaltString(SALT_SIZE);
        user.setSalt(saltString);
        String password = userRegVo.getPassword();
        user.setPassword(new Md5Hash(password, saltString).toString());
        this.userService.insert(user);
        return new Result("注册成功");
    }
}
